﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OT.Data;
using OT.Areas.Instructor.Models;

namespace OT.Areas.Instructor.Controllers
{
    public class ChangePasswordController : Controller
    {
        readonly OTEntitiesme OTDb = new OTEntitiesme();
        public ActionResult Index()
        {
            int UserID=0;
            if (Request.Cookies["LoginSesID"] != null)
            {
                UserID =Convert.ToInt16(Request.Cookies["LoginSesID"].Value);
            }
            else
            {
                Response.Redirect("~/Home");
            }
            ChangePassword ChangePass = null;
            try
            {
                var User = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                if (User != null)
                {
                    ChangePass = new ChangePassword();
                    ChangePass.Password = User.Password;
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return View();
        }
        [HttpPost]
        public string Index(string Password, string NewPassword)
        {
            string result = "";
            try
            {
                int UserID = Convert.ToInt16(Request.Cookies["LoginSesID"].Value);
                if (ModelState.IsValid)
                {
                    var User = OTDb.Users.Where(r => r.UserID == UserID).SingleOrDefault();
                    if (User != null)
                    {
                        if (User.Password == Password)
                        {
                            User.Password = NewPassword;
                            OTDb.SaveChanges();
                            result = "Sccuess";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utilities.InsertErrorLog(ex);
            }
            return result;
        }

           public int PasswordCheck(string Password)
        {
            int UserID = Convert.ToInt16(Request.Cookies["LoginSesID"].Value);
            int check = OTDb.Users.Where(u => u.UserID.Equals(UserID) && u.Password.Trim().Equals(Password)).Count<User>();
            return check;
                
        }

    }
}
